using System;

namespace Fusion.Net
{
    public struct ExceptionData
    {
        private int errorCode;

        public ExceptionData(int errorCode)
        {
            this.errorCode = errorCode;
        }

        public int ErrorCode { get => errorCode; }
    }

    public class NetBase
    {
        protected NetDataHandler dataHandler;

        protected SocketBase socket;

        public NetDataHandler DataHandler { get => dataHandler; }
        public SocketBase SocketObject { get => socket;  }

        
        protected NetBase()
        {
            dataHandler = new NetDataHandler(this);
            NetManager.Instance.Add(this);
        }

        public event Action<SocketBase, byte[]> OnMessage;
        public event Action<SocketBase, ExceptionData> OnError;
        public event Action<SocketBase, int> OnClosed;

        public event Action<SocketBase> OnHeartBeated;

        public event Action<SocketBase> OnOpen;

        public void Open()
        {
            socket?.Open();
        }

        public void InvokeOnOpen(SocketBase socket)
        {
            OnOpen?.Invoke(socket);
        }

        public void InvokeOnHeartBeated(SocketBase socket)
        {
            OnHeartBeated?.Invoke(socket);
        }

        public void InvokeOnClosed(SocketBase socket, int code)
        {
            OnClosed?.Invoke(socket, code);
        }
        public void InvokeOnMessage(SocketBase socket, byte[] data)
        {
            OnMessage?.Invoke(socket, data);
        }

        public void InvokeOnError(SocketBase socket, ExceptionData e)
        {      
            OnError?.Invoke(socket, e);
        }

        public virtual void Close(int code = 0)
        {
            if (socket != null)
            {
                socket.Close(code);
                socket = null;
            }
            dataHandler.Close();
            NetManager.Instance.Remove(this);
        }
    }
}

